<?php

namespace App\Http\Controllers\Admin;

use App\Service\PermissionService;
use App\Service\RolePermissionService;
use App\Service\RoleService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Contracts\Permission;

class RoleController extends Controller
{
    private $service;

    public function __construct(RoleService $service)
    {
        $this->service = $service;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function all()
    {
        return $this->code($this->service->repository->all());
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return $this->code($this->service->repository->orderBy('id', 'desc')->paginate($this->page));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return $this->code($this->service->repository->create([
                'guard_name' => 'admin',
                'name' => $request->name
        ]));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return $this->code($this->service->repository->find($id));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return $this->code($this->service->repository->find($id)->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return $this->code($this->service->repository->destroy($id));
    }

    /**
     * @author huangangui
     * @explain 获取角色的所有权限
     * @param RolePermissionService $rolePermissionService
     * @param $id
     * @return mixed
     */
    public function getPermissions(RolePermissionService $rolePermissionService, $id){
        $data = $rolePermissionService->repository->where('role_id', $id)->get()->toArray();
        return $this->code(array_column($data, 'permission_id'));
    }


    /**
     * @author huangangui
     * @explain 设置角色对应的权限
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function setPermission(Request $request, $id){
        return $this->code($this->service->setPermission($request->permissions, $id));
    }

}
